<?php
namespace Admin\Controller;
// use Think\Controller;
use Admin\Logic\DeviceLogic;
class DeviceController extends CommonController
{

    public function index() {
        session('page_size',$_GET['page_size']);
    	$page_no = I('get.p') ? I('get.p') : 1;
        $shop_id = I('get.shop_id') ? I('get.shop_id') : M('shop')->where('del=0')->getField('id');
        $page_size = I('get.page_size') ? I('get.page_size') : 10;
    	$data = M('device a')
    		->where(array('shop_id'=>$shop_id))
    		->page($page_no, $page_size)
    		->field('a.id,a.name,a.add_time,a.code_num,c.cate_name')
    		->join("left join zm_device_cate c on a.cate_id=c.id")
            ->order('id desc')
    		->select();
        foreach ($data as $k => $v) {
                $data[$k]['code_num'] = 'http://'.$_SERVER['HTTP_HOST'].__ROOT__.$v['code_num'];
            }    
    	$count =M('device')->where(array('shop_id'=>$shop_id))->count();
        $Page = new \AntAge\Page($count, $page_size);
        $show = $Page->show();
        $shop = M('shop')->where('del=0')->select();
        $this->assign('shop',$shop);
        $this->assign('shop_id',$shop_id);
        $this->assign('type',$_SESSION['type']);
        $this->assign('page', $show);
        $this->assign("count", $count);
        $this->assign("data", $data);
        $this->display();
    }

    // 添加
    public function deviceAdd(){
        if($_SESSION['type'] == 0){
                $this->error('你没有权限');
            }
        if (IS_POST)
        {
            $list = I('post.');
           
            $shop_id = $list['shop_id']?$list['shop_id']:$this->error('请选择客户');
            // $name = $list['name']?$list['name']:$this->error('别名不能为空');
            $cate_id = $list['cate_id']?$list['cate_id']:$this->error('请选择分类');
            $area = $list['area']?$list['area']: ' ';//$this->error('请填写位置');
            $number1 = $list['number1']?$list['number1']:$this->error('请选择起始个数');
            $number2 = $list['number2']?$list['number2']:$this->error('请选择结束个数');

            if ($number2<$number1) 
            {
                $this->error('起始个数不能大于结束个数');
            }
            $last_num = M('device')->where(array('shop_id'=>$shop_id,'cate_id'=>$cate_id))->order('id desc')->getField('end_num');

            if ($number1<=$last_num) 
            {
                $this->error('起始数只能小于上次插入结束数:'.$last_num);
            }
            $shop_name = M('shop')->where(array('id'=>$shop_id))->getField('en_name');

            $list['add_time']=time();
            $num = $number2-$number1+1;
            for ($i=0; $i <$num; $i++) { 
                $code[$i]['add_time'] =time();
                $code[$i]['cate_id']  =$list['cate_id'];
                $code[$i]['name'] = $number1.'号';
                $code[$i]['shop_id'] =$list['shop_id'];
                $code[$i]['area'] =$list['area'];//.'-'.$number1.'号';
                $code[$i]['end_num'] = $number2;
                $number1++;
            }
            // $myfile=fopen("log.txt", "w");fwrite($myfile, $num);
            $data = M('device')->addAll($code);
            $k = $list['number1'];
            for ($i=$data; $i <$data+$num ; $i++) { 
                if ($list['cate_id'] == 1) {
                    $urls[$i] = 'http://'.$_SERVER['HTTP_HOST'].__APP__.'/Home/Light/index?id='.$i;
                }
                if ($list['cate_id'] == 2) {
                    $urls[$i] = 'http://'.$_SERVER['HTTP_HOST'].__APP__.'/Home/Bait/index?id='.$i;
                }
                if ($list['cate_id'] == 3) {
                    $urls[$i] = 'http://'.$_SERVER['HTTP_HOST'].__APP__.'/Home/Glue/index?id='.$i;
                }
                if ($list['cate_id'] == 4) {
                    $urls[$i] = 'http://'.$_SERVER['HTTP_HOST'].__APP__.'/Home/Mousetrap/index?id='.$i;
                }
                if ($list['cate_id'] == 5) {
                    $urls[$i] = 'http://'.$_SERVER['HTTP_HOST'].__APP__.'/Home/Reptile/index?id='.$i;
                }
                $img = $list['cate_id'];

                
                // $names[$i] = $list['name'].'-'.$k.'号';
                $names[$i] = $k.'号';
                
                // $myfile=fopen("log.txt", "w");fwrite($myfile, $i);
                $addCode = new DeviceLogic();
                $codes[$i]=$addCode->addCode($urls[$i],$k,$img,$names[$i],$shop_name);
                $k++;
                $map['id']=$i;
                $data[$i] = M('device')->where($map)->save(array('code_num'=>$codes[$i]));
                
            }
            if ($data) {
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        } 
    	$cate = M('device_cate')->field('id,cate_name')->select();
        $shop = M('shop')->where(array('del'=>0))->field('id,shop_name')->select();
        $this->assign('type',$_SESSION['type']);
        $this->assign("cate", $cate);
        $this->assign("shop", $shop);
        $this->display();
    }
    // 删除
    public function deviceDel(){
        if($_SESSION['type'] == 0){
                $this->error('你没有权限');
            }
        $id= I('id');
        $data = M('device')->where('id='.$id)->delete();
        if ($data) {
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    public function ever_del(){
        if($_SESSION['type'] == 0)
        {
            $this->error('你没有权限');
        }
        $arr = json_decode(file_get_contents("php://input"), true);

        foreach ($arr as $key => $v) {
            $ids[] = $v['id'];
        }
        $map['id'] = array('in',$ids);
        $data = M('device')->where($map)->delete();
        if ($data) {
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
        $this->ajaxReturn($ids);
    }

    // 修改
    public function deviceUp(){
        if($_SESSION['type'] == 0){
                $this->error('你没有权限');
            }
        if (IS_POST) {
            $id = I('post.id');
            $list['cate_id'] = I('post.cate_id');
            $list['name'] = I('post.name');
            $list['area'] = I('post.area');
            $list['edit_time'] = time();
            $data = M('device')->where('id='.$id)->save($list);
            if ($data) {
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }
        $id = I('get.id');
        $data = M('device a')->field("a.id,a.cate_id,a.shop_id,a.name,a.code_num,a.area,b.shop_name")
                    ->join("left join zm_shop b on a.shop_id=b.id")->where('a.id='.$id)->find();
        $cate = M('device_cate')->field('id,cate_name')->select();
        $this->assign('type',$_SESSION['type']);
        $this->assign("cate", $cate);
        $this->assign("data", $data);
        $this->display();

    }
    // 分类 列表
    public function cate(){
        session('page_size',$_GET['page_size']);
        $page_no = I('get.p') ? I('get.p') : 1;
        $page_size = I('get.page_size') ? I('get.page_size') : 10;
        $data = M('device_cate')
            ->where()
            ->page($page_no, $page_size)
            ->select();
        $count =M('device_cate')->where()->count();
        $Page = new \AntAge\Page($count, $page_size);
        $show = $Page->show();
        $this->assign('type',$_SESSION['type']);
        $this->assign('page', $show);
        $this->assign("count", $count);
        $this->assign("data", $data);
        $this->display();
    }
    // 分类 添加
    public function cateAdd(){
        if ($_POST) {
            $pest = implode(',', $_POST['pest_cate']);
            $data = array(
                'cate_name' => I('post.cate_name'),
                'add_time'  => time(),
                'status'    => I('post.status'),
                'explanation'=> I('post.explanation'),
                'pest'      => $pest,
            );
            //检查是否为空
            if (!$_POST['pest_cate']) {
                $this->error('请选择需要捕获的害虫');
            }
            if (!$data['cate_name']) {
                $this->error('请填写类型名称');
            }
            //检查分类是否重复
            $cate_name = M('device_cate')->getField('cate_name',true);
            if (in_array($data['cate_name'], $cate_name)) {
                $this->error('此分类已经存在');
            }
            //添加数据
            $res = M('device_cate')->add($data);
            if ($res) {
                $this->success("添加成功");
            }else{
                $this->error('添加失败');
            }
        }else{
            $animal = M('animal')->select();
            $this->assign('type',$_SESSION['type']);
            $this->assign('animal',$animal);
            $this->display();
        }
    }

    // 分类 删除
    public function cateDel(){
        $id= I('post.id');
        $data = M('device_cate')->where('id='.$id)->delete();
        if ($data) {
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    // 分类 修改
    public function cateUp(){
        if ($_POST) {
            $id = I('post.id');
            $pest = implode(',', $_POST['pest_cate']);
            $data = array(
                'cate_name' => I('post.cate_name'),
                'status'    => I('post.status'),
                'explanation'=> I('post.explanation'),
                'pest'      => $pest,
            );
            //检查是否为空
            if (!$_POST['pest_cate']) {
                $this->error('请选择需要捕获的害虫');
            }
            if (!$data['cate_name']) {
                $this->error('请填写类型名称');
            }
            //检查分类是否重复
            $name = M('device_cate')->where('id='.$id)->getField('cate_name');
            if ($name != $data['cate_name']) {
                $cate_name = M('device_cate')->getField('cate_name',true);
                if (in_array($data['cate_name'], $cate_name)) {
                    $this->error('此分类已经存在');
                }
            }
            //添加数据
            $res = M('device_cate')->where(array('id'=>$id))->save($data);
            if ($res === false) {
                $this->error("修改失败");
            }else{
                $this->success('修改成功');
            }
        }else{
            $id=I('id');
            if ($id) {
                $animal = M('animal')->select();
                $data = M('device_cate')->where(array('id'=>$id))->find();
                $pest = explode(',', $data['pest']);
                $this->assign('type',$_SESSION['type']);
                $this->assign('animal',$animal);
                $this->assign('data',$data);
                $this->assign('pest',$pest);
                $this->display();
            }
        }
    }
    public function animal(){
        session('page_size',$_GET['page_size']);
        $page_no = I('get.p') ? I('get.p') : 1;
        $page_size = I('get.page_size') ? I('get.page_size') : 10;
        $data = M('animal')
            ->where()
            ->page($page_no, $page_size)
            ->field('id,name,ename')
            ->select();
        $count =M('animal')->where()->count();
        $Page = new \AntAge\Page($count, $page_size);
        $show = $Page->show();
        $this->assign('type',$_SESSION['type']);
        $this->assign('page', $show);
        $this->assign("count", $count);
        $this->assign("data", $data);
        $this->display();
    }
    public function animalAdd(){
        if ($_POST) {
            $data = array(
                'name' => $_POST['name'],
                'ename' => $_POST['ename']
            );
            $names = M('animal')->getField('name',true);
            if (in_array($data['name'], $names)) {
                $this->error('重复添加');
            }else{
                $res = M('animal')->add($data);
                if ($res) {
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            }
        }else{
            $this->display();
        }
        
    }
    public function animalDel(){
        $id = I('id');
        if ($id) {
            $res = M('animal')->delete($id);
            if ($res) {
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }else{
            $this->error('参数错误');  
        }
    }


    //下载二维码
    public function downloads(){

        import('ORG.Util.FileToZip');
        // 打包下载
        $id = I('get.id');
        $fled = M('shop')->where(array('id'=>$id))->getField('en_name');
        $cur_file = 'Public/Uploads/Company/2017code/'.$fled;
        $handler = opendir($cur_file);    //$cur_file 文件所在目录
        $download_file = array();
        $i = 0;
        while( ($filename = readdir($handler)) !== false ) {
            if($filename != '.' && $filename != '..') {
                $download_file[$i++] = $filename;
            }
        }
        $save_path = 'Public/Uploads/Company/2017code';
        closedir($handler);
        $scandir=new \traverseDir($cur_file,$save_path);    //$save_path zip包文件目录
        $scandir->tozip($download_file,$fled);
        // dump();exit();

    }

    public function download(){

        $id = I('get.id');
        $file = M('device')->where(array('id'=>$id))->getField('code_num');
        // $file='./Public/Uploads/Company/20170224/qrcode_2251487922189.png';
        $fileName = $name ? $name : pathinfo($file,PATHINFO_FILENAME);
        $filePath = realpath($file);
        
        $fp = fopen($filePath,'rb');
        
        if(!$filePath || !$fp){
            header('HTTP/1.1 404 Not Found');
            echo "Error: 404 Not Found.(server file path error)<!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding -->";
            exit;
        }
        
        $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION);
        $encoded_filename = urlencode($fileName);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);
        
        header('HTTP/1.1 200 OK');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Content-type: image/png");
        header("Content-Length: ".filesize($filePath));
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".filesize($filePath));
        
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
        }
        
        // ob_end_clean(); <--有些情况可能需要调用此函数
        ob_clean();
        // 输出文件内容
        fpassthru($fp);
        exit;
    }

    public function image(){

        $image = new \Think\Image(); // 在图片右下角添加水印文字 ThinkPHP 并保存为new.jpg

        $image->open('./ddd.png')->crop(450, 450)->save('./water.jpg');//将图片裁剪为400x400并保存为corp.jpg
        // $image->crop(450, 450)->save('./water.jpg');

        // $image->open('./ddd.png')->water('./sss.png',\Think\Image::IMAGE_WATER_NORTHWEST,50)->save("water.jpg"); 

        $data =$image->open('./water.jpg')
        ->text('你好sss','./simsun.ttc',20,'#000000',\Think\Image::IMAGE_WATER_SOUTH)->save("new.png");
        dump($data);exit();
    }
}